﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Workflow;

namespace SmartSpace.WebApp.Modules.Workflow.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WFButton runat=server></{0}:WFButton>")]
    public class WFButton : Button
    {
        public WorkflowInstance WfInstance { get; set; }
        public EventMetadata WfEvent { get; set; }

        public List<string> SelectedUser { get; set; }

        public WFButton(WorkflowInstance instance, EventMetadata @event)
        {
            WfInstance = instance;
            WfEvent = @event;
        }

        protected override void OnInit(EventArgs e)
        {
            if (WfEvent.IsNeedPickUser)
            {
                OnClientClick = "return on" + this.ClientID + "Click();";
            }
            base.OnInit(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (WfEvent.IsNeedPickUser)
            {
                string pageUrl = this.Page.ResolveClientUrl("~/Modules/Workflow/Pages/User-Picker.aspx");
                pageUrl = pageUrl + "?module=" + WfInstance.RefModule + "&wfid=" + WfEvent.WorkflowId.ToString() + "&actid=" + WfEvent.ToActivityId.ToString();
                writer.Write("<script>function on" + this.ClientID + "Click(){ var result = _ss.dlg('" + pageUrl + "'); if(result==null){ return false;}else{$('#" + this.ClientID + "_value_').val(result[1].value); return true;}}</script>");
                writer.WriteLine("<input type='hidden' id='" + this.ClientID + "_value_' name='" + this.ClientID + "_value_'/>");
            }
            else
            {
                writer.WriteLine("<input type='hidden' id='" + this.ClientID + "_value_' name='" + this.ClientID + "_value_' value='" + WfInstance.Creator + "'/>");
            }
            base.Render(writer);
        }

        protected override void OnClick(EventArgs e)
        {
            SelectedUser = new List<string>();
            SelectedUser.Add(this.Page.Request.Form[this.ClientID + "_value_"]);
            base.OnClick(e);
        }
    }
}
